package com.requiem.hist_group_manage_springboot.common;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;


//分页工具类
@Component
public class PageUtil {

    public Integer[] parsePageParams(Map<String, String> params) {
        if (params == null) {
            return null;
        }

        String pageNumStr = params.get("pageNum");
        String pageSizeStr = params.get("pageSize");

        // 必须同时存在pageNum和pageSize才启用分页
        if (!StringUtils.hasText(pageNumStr) || !StringUtils.hasText(pageSizeStr)) {
            return null;
        }

        try {
            Integer pageNum = Integer.parseInt(pageNumStr);
            Integer pageSize = Integer.parseInt(pageSizeStr);

            // 校验分页参数有效性
            if (pageNum < 1) pageNum = 1;
            if (pageSize < 1) pageSize = 10;

            return new Integer[]{pageNum, pageSize};
        } catch (NumberFormatException ignored) {
            return null;
        }
    }

    public <T> Map<String, Object> executePageQuery(Map<String, String> params, Supplier<List<T>> querySupplier) {
        Integer[] pageParams = parsePageParams(params);
        Map<String, Object> result = new HashMap<>();
        List<T> dataList;

        // 判断是否需要分页
        if (pageParams != null) {
            Integer pageNum = pageParams[0];
            Integer pageSize = pageParams[1];

            // 开启分页
            PageHelper.startPage(pageNum, pageSize);
            dataList = querySupplier.get(); // 执行分页查询

            // 处理分页结果
            if (dataList instanceof Page<T> pageResult) {
                result.put("list", pageResult.getResult());
                result.put("total", pageResult.getTotal());
                result.put("pages", pageResult.getPages());
                result.put("pageNum", pageNum);
                result.put("pageSize", pageSize);
            } else {
                result.put("list", dataList);
                result.put("total", dataList.size());
            }
        } else {
            // 不分页，返回全部数据
            dataList = querySupplier.get();
            result.put("list", dataList);
            result.put("total", dataList.size());
        }

        return result;
    }
}
